document.write('<script type="text/javascript" src="'+jsHostBase+'js/uploader/swfupload.js"></script>');
document.write('<script type="text/javascript" src="'+jsHostBase+'js/uploader/lang/zh-cn.js"></script>');


/**
* 图片上传
*/
var uploader = new function () {
    this.instance = null;
    this.settings;
	
    /**
    * 初始化
    * 
    * @param json opts
    */
    this.init = function (opts) {
        var settings = {
            flash_url: jsHostBase+'js/uploader/swfupload.swf',
            upload_url: 'upload_url',
            post_params: {}, // json格式
            file_size_limit: "450KB",
            file_types: "*.jpg;*.gif;*.png",
            file_types_description: "图片",
            file_upload_limit: 0,
            file_queue_limit: 0,
            file_post_name: 'file',
            custom_settings: { progressTarget: 'fsUploadProgress' },

            debug: false,

            // Button settings
            button_image_url: jsHostBase+"js/uploader/images/add.gif",
            button_width: 80,
            button_height: 17,
            button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
            button_cursor: SWFUpload.CURSOR.HAND,
            button_placeholder_id: 'divAddFiles',
            button_text: '<span class="theFont">上传图片</span>',
            button_text_style: ".theFont {color:#444444; font-weight:bold; }",
            button_text_left_padding: 20,
            button_text_top_padding: 0,

            file_queued_handler: fileQueued,
            file_queue_error_handler: fileQueueError,
            file_dialog_complete_handler: fileDialogComplete,
            queue_complete_handler: queueComplete,
            upload_start_handler: uploadStart,
            upload_progress_handler: uploadProgress,
            upload_error_handler: uploadError,
            upload_success_handler: this.uploadFinishHandler,
            upload_complete_handler: uploadComplete
        };

        // 设置覆盖默认配置
        for (var i in opts) {
            settings[i] = opts[i];
        }

        if (settings.is_single_image) {
            settings.file_queue_limit = 1;
        }
		
		// 替换按钮
		var btnText = $('#' + settings.button_placeholder_id).text();
        $('#' + settings.button_placeholder_id).removeAttr('disabled');
        var btnHtml = '<label class="btn-upload"><span><b id="' + settings.button_placeholder_id + '">'
		            +   btnText
					+ '</b></span></label>';
        $('#' + settings.button_placeholder_id).replaceWith(btnHtml);

        if ($('#' + settings.custom_settings.progressTarget).length <= 0) {
            $('body').append('<div id="' + settings.custom_settings.progressTarget + '"></div>');
        }
		
		// 按钮文字
		if(btnText != '') {
			settings.button_text = '<span class="theFont">'+ btnText +'</span>';
		}

        
        // 上传地址及参数
		settings.upload_url = uploadUrl;
		settings.upload_url += uploadUrl.indexOf('?') == -1 ? '?' : '';
        settings.upload_url += '&' + json2Reqstr(settings.post_params);
        
        this.settings = settings;

        this.instance = new SWFUpload(settings);
    };

    /**
    * 覆盖该函数来自定义处理结果
    */
    this.uploadFinishHandler = function (file, r) {
		//alert(r);
        try {
            eval('var r = ' + r);
			if(!checkAjaxReturn(r)) return false;
        } catch (e) {
            alert(e+"\n"+r);
            return false;
        }
		
		var thumb = r.thumb.substr(0, 7) == 'http://' ? r.thumb : uploadBase + r.thumb;
		var img_id = r.img_id;
		var img = r.img;
		
		thumb += '?rand=' + Math.random();
		
        _this = this;        

        // 只允许有一张图片
        if (_this.settings.is_single_image) {
            $('#' + _this.settings.post_photos_id + ' img').attr('src', thumb);
            $('#' + _this.settings.post_photos_id + ' img').attr('imgid', img_id);
            $('#' + _this.settings.post_photos_id + ' img').attr('id', img_id);
            $('#' + _this.settings.post_photos_id + ' img').attr('img', img);
        } else {
			// 多张图片
            // 去掉占位图片
            if ($('#' + _this.settings.post_photos_id + ' img').hasClass('tmp-img')) {
                $('#' + _this.settings.post_photos_id + ' .tmp-img').remove();
                $('#post-photo-' + img_id).click();
            }

            var img = '<li>'
		        + '  <img width="110" height="110" img="' + img + '" imgid="' + img_id + '" id="' + img_id + '" src="' + thumb + '" class="thumb ' + _this.settings.cover_filed_id + '_item" />'
				+ '  <a class="icon-src" href="' + img + '" target="_blank"></a>'
				+ '  <a class="icon-del" href="javascript:;"></a>'
				+ '  <a class="icon-cite" href="javascript:;"></a>'
				+ '</li>';
            $('#' + _this.settings.post_photos_id).append(img);
        }

        // 添加删除图标        
        if ($('#' + img_id).parent().find('.delete').length <= 0) {
            $('#' + img_id).parent().append('<span class="delete"></span>');
        }
        // 绑定删除图片功能
        $('#' + img_id).parent().find('.delete').unbind();
        $('#' + img_id).parent().find('.delete').click(function () {
            if (!confirm('确定要删除吗？')) {
                return false;
            }

            $.ajaxf.get(delImgUrl, 'img_id=' + img_id, function (dr) {
				try {
                    eval("var dr = " + dr);
					if (dr.err) {
						alert(dr.err);
						return false;
					}
				} catch(e){
					alert(dr);
					return false;
				}

                if ($('#' + img_id).hasClass('current')) {
                    $('#' + img_id).removeClass('current');

                    // 设置另外的图片为封面图片
                    var coverItems = $('.' + _this.settings.cover_filed_id + '_item');
                    var hasResetCover = false; // 删除图片后是否还有图片可以设置为封面

                    for (var ci = 0; ci < coverItems.length; ci++) {
                        if (coverItems[ci].id != img_id) {
                            $('#' + coverItems[ci].id).click();
                            hasResetCover = true;
                            break;
                        }
                    }

                    if (!hasResetCover) {
                        hasResetCover = null;
                        $('#' + _this.settings.cover_filed_id).val('');
                        $('#' + _this.settings.cover_img_filed_id).val('');
                    }
                }

                $('#' + img_id).unbind();
                $('#' + img_id).removeClass(_this.settings.cover_filed_id + '_item');
                $('#' + img_id).parent().find('.delete').remove();
                $('#' + img_id).attr('src', tmpImgUrl);
            });

        });

        // 封面设置
        if (_this.settings.is_set_cover) {
            // 封面图片id			
            if ($('#' + _this.settings.cover_filed_id).length <= 0) {
                var input = '<input type="hidden" name="' + _this.settings.cover_filed_id + '" id="' + _this.settings.cover_filed_id + '" value="' + r.img_id + '" />';
                $('#' + _this.settings.post_photos_id).append(input);
                $('#' + r.img_id).addClass('current');
            } else if ($('#' + _this.settings.cover_filed_id).val() == '' || _this.settings.force_set_cover) {
                $('#' + _this.settings.cover_filed_id).val(r.img_id);
                $('#' + r.img_id).addClass('current');
            }

            // 封面图片地址
            if (typeof _this.settings.cover_img_filed_id != 'undefined') {
                if ($('#' + _this.settings.cover_img_filed_id).length <= 0) {
                    var input = '<input type="hidden" name="' + _this.settings.cover_img_filed_id + '" id="' + _this.settings.cover_img_filed_id + '" value="' + img + '" />';
                    $('#' + _this.settings.post_photos_id).append(input);
                    $('#' + img_id).addClass('current');
                } else if ($('#' + _this.settings.cover_img_filed_id).val() == '') {
                    $('#' + _this.settings.cover_img_filed_id).val(img);
                    $('#' + img_id).addClass('current');
                }
            }

            // 点击图片设为封面的样式设置
            $('#' + img_id).addClass(_this.settings.cover_filed_id + '_item');
            $('#' + img_id).unbind();
            // 绑定设置图片封面功能
            $('#' + img_id).click(function () {
                ajaxStatusStart();
                $.ajaxf.get(setAlbumCoverUrl, 'id=' + img_id + '&upload_rid='+_this.settings.params.upload_rid, function (cr) {
                    try {
                        eval('var cr = ' + cr);
                        if (cr.err.length === 0) {
                            $('.' + _this.settings.cover_filed_id + '_item.current').removeClass('current');
                            $('#' + img_id).addClass('current');
                            $('#' + _this.settings.cover_img_filed_id).val($('#' + r.img_id).attr('img'));  // 设置封面图片地址
                            $('#' + _this.settings.cover_filed_id).val($('#' + r.img_id).attr('imgid'));   // 设置封面图片id
                            ajaxStatusStop();
                        }
                    } catch (e) {
                        alert(e);
                    }
                });
            });
        }
    }

    /**
    * 上传单个图片
    * 
    * @param json params 传递参数 { 'ent_id': '企业id', type: 'album', 'pid': '产品id' } type和pid可选
    * @param string btnId 按钮id
    * @param string imgParentId 显示图片的父元素id
    * @param string inputId 图片上传后图片id赋值到隐藏域的id(可选）
    * @param string coverImgFiledId 图片上传后图片地址赋值到隐藏域的id(可选）
    */
    this.uploadSingleImage = function (params, btnId, imgParentId, inputId, coverImgFiledId, opts) {
		opts = opts || {};	
		opts.force_set_cover = opts.force_set_cover || false;  // 是否设置封面
		opts.is_set_cover = true;  // 是否设置封面
		opts.is_single_image = true;  // 是否显示单张图片
		opts.button_placeholder_id = btnId;  // 按钮id                   
		opts.post_photos_id = imgParentId;
		opts.post_params = params;

        opts.cover_filed_id = inputId || null; //返回结果赋值到输入框的id    
		opts.cover_img_filed_id = coverImgFiledId || null; //返回结果赋值到输入框的id    

        this.init(opts);
    }

    this.uploadImages = function (params, btnId, imgParentId, inputId, coverImgFiledId, opts) {
		opts.is_set_cover = true;  // 是否设置封面
		opts.is_single_image = false;  // 是否显示单张图片
		opts.button_placeholder_id = btnId;  // 按钮id                   
		opts.post_photos_id = imgParentId;
		opts.post_params = params;

        opts.cover_filed_id = inputId || null; //返回结果赋值到输入框的id
        opts.cover_img_filed_id = coverImgFiledId || null; //返回结果赋值到输入框的id 

        this.init(opts);
    }
}

/**
 * 创建商品相册上传功能
 *
 * @param string div_id 上传功能嵌入层id
 * @param string cover_id_input 上传成功后图片id复制到的输入框的name和id(可选)
 * @param string cover_img_input 上传成功后图片地址复制到的输入框的name和id(可选)
 * @param int opts 重置swfuploa配置信息，如果有和params则被被params替换 (可选)
 * @param int ps_num 相册图片个数 (可选)
 */
function albumAdd(div_id, params, cover_id_input, cover_img_input, opts, ps_num) {
	params = params || {};
	params.upload_type = 'album';
	
	opts = opts || {};
	opts.force_set_cover = opts.force_set_cover || false;
    ps_num = ps_num || 3;	
    cover_id_input = cover_id_input || 'cover_id_input';
	cover_img_input = cover_img_input || Math.random()*100000000000000000;
		
    var html = '<div class="ue-album-box"><ul>';
    for (var i = 1; i <= ps_num; i++) {
        html += '<li>'
              + '  <p><span id="'+cover_id_input+'_album_img_' + i + '"><img src="'+tmpImgUrl+'" title="点击图片设为产品封面" class="thumb"/></span></p>'
              + '  <p style="text-align:center; padding-top:8px;">'
              + '    <b id="bun-album-add-' + i + '" disabled="disabled">上传图片</b>'
              + '  </p>'
              + '</li>';
    }

    html += '</ul></div>';
    $('#' + div_id).append(html);
    
    // 上传按钮
    for (var i = 1; i <= ps_num; i++) {		
		params.upload_sort = i;
        uploader.uploadSingleImage(params, 'bun-album-add-' + i, cover_id_input+'_album_img_' + i, cover_id_input, cover_img_input, opts);
    }
}

/**
 * 创建商品相册上传功能
 *
 * @param string div_id 上传功能嵌入层id
 * @param string cover_id_input 上传成功后图片id复制到的输入框的name和id(可选)
 * @param string cover_img_input 上传成功后图片地址复制到的输入框的name和id(可选)
 * @param int ps_num 相册图片个数 (可选)
 */
function albumEdit(div_id, params, cover_id_input, cover_img_input, opts, ps_num) {
	params = params || {};
	params.upload_type = 'album';
	
	opts = opts || {};
	opts.cover_rid = opts.cover_rid || null;
	opts.force_set_cover = opts.force_set_cover || false;
    ps_num = ps_num || 3;	
    cover_id_input = cover_id_input || 'cover_id_input';
	cover_img_input = cover_img_input || Math.random()*100000000000000000;
		
    var html = '<div class="ue-album-box"><ul>';
    for (var i = 1; i <= ps_num; i++) {
        html += '<li>'
              + '  <p><span id="'+cover_id_input+'_album_img_' + i + '"><img src="'+tmpImgUrl+'" title="点击图片设为产品封面" class="thumb"/></span></p>'
              + '  <p style="text-align:center; padding-top:8px;">'
              + '    <b id="bun-album-add-' + i + '" disabled="disabled">上传图片</b>'
              + '  </p>'
              + '</li>';
    }

    html += '</ul></div>';
    $('#' + div_id).append(html);
    
    $.ajaxf.ready(function () {
        // 获取图片
        ajaxStatusStart();		
		
        $.ajaxf.getJSON(getAlbumImgsUrl, json2Reqstr(params), function (rAlbum) {
            try {
                if (rAlbum.err) {
                    alert(rAlbum.err.text);
                    return false;
                }
            } catch (e) {
                alert(e+"\n"+rAlbum);
            }

			var album = rAlbum.images;
			for (var id in album) {
				var img_id = album[id].img_id;
				var img    = album[id].img;
				var sort   = album[id].sort;
				var thumb  = (album[id].thumb.substr(0, 7) == 'http://' ? album[id].thumb : uploadBase + album[id].thumb) + '?rand=' + Math.random();
				
				$('#'+cover_id_input+'_album_img_' + sort + ' img').attr('src', thumb);
				$('#'+cover_id_input+'_album_img_' + sort + ' img').attr('imgid', img_id);
				$('#'+cover_id_input+'_album_img_' + sort + ' img').attr('id', img_id);
				$('#'+cover_id_input+'_album_img_' + sort + ' img').attr('img', img);
				$('#' + img_id).addClass(cover_id_input + '_item');
				$('#' + img_id).parent().append('<span class="delete"></span>');

				// 封面图片
				if (opts.cover_rid == img_id) {
					// 点击图片设为封面的样式设置                     
					$('#' + cover_id_input).val(img_id);
					$('#' + img_id).addClass('current');
					var input = '<input type="hidden" name="' + cover_id_input + '" id="' + cover_id_input + '" value="' + img_id + '" />';
					$('#' + img_id).parent().append().append(input);
					if (typeof cover_img_input != 'undefined') {
						var input = '<input type="hidden" name="' + cover_img_input + '" id="' + cover_img_input + '" value="' + img + '" />';
						$('#' + img_id).parent().append().append(input);
					}
				}

				// 绑定设置图片封面功能
				$('#' + img_id).unbind();
				$('#' + img_id).click(function () {
					var coverid = $(this).attr('imgid');
					var coverImg = $(this).attr('img');		
					$('.' + cover_id_input + '_item.current').removeClass('current');
					$('#' + coverid).addClass('current');
					$('#' + cover_id_input).val(coverid);  // 设置封面图片地址
					$('#' + cover_img_input).val(coverImg); // 设置封面图片id
				});

				// 删除图片
				$('#' + img_id).parent().find('.delete').unbind();
				$('#' + img_id).parent().find('.delete').click(function () {
					if (!confirm('确定要删除吗？')) {
						return false;
					}
					var imgid = $(this).parent().find('.' + cover_id_input + '_item').attr('imgid');
					
					$.ajaxf.get(delImgUrl, 'id=' + imgid, function (dr) {
						try{
						    eval("var dr = " + dr);
							if (dr.err) {
								alert(dr.err);
								return false;
							}							
						} catch (e) {
							alert(dr);
							return false;
						}

						if ($('#' + imgid).hasClass('current')) {
							$('#' + imgid).removeClass('current');

							// 设置另外的图片为封面图片
							var coverItems = $('.' + cover_id_input + '_item');
							var hasResetCover = false; // 删除图片后是否还有图片可以设置为封面

							for (var ci = 0; ci < coverItems.length; ci++) {
								if (coverItems[ci]['id'] != imgid) {
									$('#' + coverItems[ci]['id']).click();
									hasResetCover = true;
									break;
								}
							}

							if (!hasResetCover) {
								hasResetCover = null;
								$('#' + cover_id_input).val('');
								$('#' + cover_img_input).val('');
							}
						}

						$('#' + imgid).unbind();
						$('#' + imgid).parent().find('.delete').remove();
						$('#' + imgid).attr('src', tmpImgUrl);
					});

				});

			}
			    
			// 上传按钮
			for (var i = 1; i <= ps_num; i++) {		
				params.upload_sort = i;
				params.upload_id = $('#'+cover_id_input+'_album_img_'+ i + ' img').attr('id');				
				uploader.uploadSingleImage(params, 'bun-album-add-' + i, cover_id_input+'_album_img_'+ i, cover_id_input, cover_img_input, opts);
			}
			
			ajaxStatusStop();
        });
    });
}
